package com.kye.express.business.president_online;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.github.piasy.rxandroidaudio.PlayConfig;
import com.github.piasy.rxandroidaudio.RxAudioPlayer;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatFragment;
import com.kye.express.business.login.LoginActivity;
import com.kye.express.databinding.FragmentPresidentOnlineDetailBinding;
import com.kye.express.utils.Base64FileUtils;
import com.kye.express.utils.DateTimeUtils;
import com.kye.express.utils.ImageUtils;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.utils.StringUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.express.view.VoiceSoundView;
import com.kye.model.bean.president_online.PresidentOnlineListBean;
import com.kye.model.bean.president_online.PresidentOnlineResBean;
import com.kye.model.bean.president_online.PresidentOnlineScoreBean;
import com.kye.model.bean.user.User;
import com.kye.model.constant.Constants;

import java.io.File;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * 总裁热线--留言详情
 */
public class PresidentOnlineDetailFragment extends BaseAppCompatFragment implements PresidentOnlineDetailFragmentContract.PresidentOnlineDetailView {
    private static final String ARG_DATA = "data";
    private FragmentPresidentOnlineDetailBinding mBinding;
    private PresidentOnlineDetailFragmentContract.PresidentOnlineDetailViewPresenter mPresenter;
    private Dialog mKyeLoadingDialog;
    private PresidentOnlineListBean.DatasBean mData;
    private RxAudioPlayer mRxAudioPlayer;

    public static PresidentOnlineDetailFragment newInstance(PresidentOnlineListBean.DatasBean datasBean) {
        PresidentOnlineDetailFragment fragment = new PresidentOnlineDetailFragment();
        if (datasBean != null) {
            Bundle bundle = new Bundle();
            bundle.putSerializable(ARG_DATA, datasBean);
            fragment.setArguments(bundle);
        }
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_president_online_detail, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        getActivity().setTitle(getString(R.string.president_online_detail));
        Bundle bundle = getArguments();
        if (bundle != null) {
            mData = (PresidentOnlineListBean.DatasBean) bundle.getSerializable(ARG_DATA);
        }
        if (mData != null) {
            mBinding = FragmentPresidentOnlineDetailBinding.bind(view);
            mPresenter = new PresidentOnlineDetailFragmentContract.PresidentOnlineDetailViewPresenter(getActivity());
            mPresenter.bind(this);
            initView();
            initEvent();
        }
    }

    private void initView() {
        try {
            mBinding.edtInfo.setText(mData.getMessage());
            mBinding.edtReply.setText(mData.getReply());
            mBinding.tvStatus.setText(mData.getHandleStatus());
            String time = mData.getCreateTime().replaceAll("T", " ");

            String time1 = DateTimeUtils.getStringDateByMounthDay(DateTimeUtils.getOderTime(time));
            mBinding.tvDate.setText(time1);

            if (StringUtils.isNullOrEmpty(mData.getAudioSrc())) {
                //            文本留言信息
                mBinding.edtInfo.setVisibility(View.VISIBLE);
                mBinding.rlTrialDetailLeave.setVisibility(View.GONE);
            } else {
                //            语音留言信息
                String s = StringUtils.formartDeleteZero(mData.getAudioSize() + "");
                mBinding.tvLeavedetailTimeLeave.setText(s + "\"");
                mBinding.edtInfo.setVisibility(View.GONE);
                mBinding.rlTrialDetailLeave.setVisibility(View.VISIBLE);
            }

            if (StringUtils.isNullOrEmpty(mData.getReplyAudioSrc())) {
                //            回复信息为文本
                mBinding.rlTrialDetail.setVisibility(View.GONE);
                mBinding.edtReply.setVisibility(View.VISIBLE);
            } else {
                //            回复信息为语音
                mBinding.rlTrialDetail.setVisibility(View.VISIBLE);
                mBinding.edtReply.setVisibility(View.GONE);
            }

            if (mData.isIsImage()) {
                mPresenter.onUser(mPresenter.TYPE_RES_IMAGE);
                mBinding.rlUploadPic.setVisibility(View.VISIBLE);
            }
            mBinding.leaveLayout.setVisibility(View.VISIBLE);
            if (mData.isIsOver()) {
                //如果评价为空
                if (StringUtils.isNullOrEmpty(mData.getComment())) {
                    mBinding.rbOne.setEnabled(true);
                    mBinding.btnSubmit.setVisibility(View.VISIBLE);
                } else {
                    mBinding.rbOne.setEnabled(false);
                    mBinding.rbTwo.setEnabled(false);
                    mBinding.rbThree.setEnabled(false);
                    mBinding.btnSubmit.setVisibility(View.GONE);
                    if (mData.getComment().equals("满意")) {
                        mBinding.rbOne.setButtonDrawable(R.mipmap.icon_leave_true_1);
                    } else if (mData.getComment().equals("一般")) {
                        mBinding.rbTwo.setButtonDrawable(R.mipmap.icon_leave_true_1);
                    } else if (mData.getComment().equals("不满意")) {
                        mBinding.rbThree.setButtonDrawable(R.mipmap.icon_leave_true_1);
                        mBinding.edtCause.setVisibility(View.VISIBLE);
                        mBinding.edtCause.setEnabled(false);
                        mBinding.edtCause.setText(StringUtils.checkStringIsNull(mData.getCommentDetail()));
                    }
                }
            } else {
                mBinding.leaveLayout.setVisibility(View.GONE);
                mBinding.btnSubmit.setVisibility(View.GONE);
            }
            mRxAudioPlayer = RxAudioPlayer.getInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initEvent() {
        //留言语音
        RxView.clicks(mBinding.rlTrialDetailLeave)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.onUser(mPresenter.TYPE_RES_VOICE);
                    }
                });
        //回复语音
        RxView.clicks(mBinding.rlTrialDetail)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.onUser(mPresenter.TYPE_RES_VOICE_REPLAY);
                    }
                });

        mBinding.rgView.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_three) {
                    mBinding.edtCause.setVisibility(View.VISIBLE);
                } else {
                    mBinding.edtCause.setVisibility(View.GONE);
                }
            }
        });
        RxView.clicks(mBinding.btnSubmit)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycle())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String message = mBinding.edtCause.getText().toString().trim();
                        if (mBinding.rbThree.isChecked() && message.length() < 10) {
                            ToastManager.show(getActivity(), R.string.president_online_reason, Toast.LENGTH_SHORT);
                            return;
                        }
                        mPresenter.onUser(mPresenter.TYPE_SCORE);
                    }
                });
    }

    @Override
    public void onCompleteRes() {
        if (mKyeLoadingDialog != null && mKyeLoadingDialog.isShowing()) {
            mKyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadingRes() {

    }

    @Override
    public void onLoadedRes(PresidentOnlineResBean bean) {
        if (bean != null) {
            if ("0".equals(bean.getCodeType())) {
                //  图片
                List<String> images = bean.getPicture();
                if (images != null){
                    for (int i = 0; i < images.size(); i++) {
                        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ScreenUtils.dp2px(getActivity(), 65), ScreenUtils.dp2px(getActivity(), 65));
                        final ImageView photoView = new ImageView(getActivity());
                        params.rightMargin = ScreenUtils.dp2px(getActivity(), 10);
                        photoView.setLayoutParams(params);
                        photoView.setScaleType(ImageView.ScaleType.FIT_XY);
                        final Bitmap bitmap = ImageUtils.Base64StringToBitmap(images.get(i));
                        if (bitmap != null) {
                            photoView.setImageBitmap(bitmap);
                            photoView.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                }
                            });
                        }
                        mBinding.llPicContainer.addView(photoView);
                    }
                }
            } else if ("1".equals(bean.getCodeType())) {
                //  语音留言
                String autoSrc = bean.getAudio().getAudioBs64();
                String s = mData.getCode() + "leave.file.m4a";
                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator+Constants.SDCARD_FOLDER_NAME;
                try {
                    Base64FileUtils.saveFileToLocal(filePath, s, autoSrc);
                    startPlay(filePath + File.separator + s, mBinding.ivDetailAnimLeave);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if ("2".equals(bean.getCodeType())) {
                //  回复语音
                String autoSrc = bean.getAudio().getAudioBs64();
                String s = mData.getCode() + "leave.file.m4a";
                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath()
                        + File.separator+Constants.SDCARD_FOLDER_NAME;
                try {
                    Base64FileUtils.saveFileToLocal(filePath, s, autoSrc);
                    startPlay(filePath + File.separator + s, mBinding.ivDetailAnim);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onErrorRes(String msg) {
        ToastManager.show(getActivity(), msg, Toast.LENGTH_SHORT);
        if (mKyeLoadingDialog != null && mKyeLoadingDialog.isShowing()) {
            mKyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onCompleteScore() {
        if (mKyeLoadingDialog != null && mKyeLoadingDialog.isShowing()) {
            mKyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadingScore() {
        if (mKyeLoadingDialog == null) {
            mKyeLoadingDialog = new KyeProgressDialog.Builder(getActivity())
                    .build();
        }
        mKyeLoadingDialog.show();
    }

    @Override
    public void onLoadedScore(PresidentOnlineScoreBean presidentOnlineScoreBean) {
        ToastManager.show(getActivity(), getString(R.string.president_online_commit_success), Toast.LENGTH_SHORT);
        if (mKyeLoadingDialog != null && mKyeLoadingDialog.isShowing()) {
            mKyeLoadingDialog.dismiss();
        }
        getActivity().onBackPressed();
    }

    @Override
    public void onErrorScore(String msg) {
        if (mKyeLoadingDialog != null && mKyeLoadingDialog.isShowing()) {
            mKyeLoadingDialog.dismiss();
        }
    }

    @Override
    public void onUser(User user, int type) {
        if (user != null && !TextUtils.isEmpty(user.getToken())) {
            if (type == mPresenter.TYPE_RES_IMAGE) {
                mPresenter.loadResDatas(mData.getGuid(), "0");
            } else if (type == mPresenter.TYPE_RES_VOICE) {
                mPresenter.loadResDatas(mData.getGuid(), "1");
            } else if (type == mPresenter.TYPE_RES_VOICE_REPLAY) {
                mPresenter.loadResDatas(mData.getGuid(), "2");
            } else if (type == mPresenter.TYPE_RES_VOICE_FORWARD) {
                mPresenter.loadResDatas(mData.getGuid(), "3");
            } else if (type == mPresenter.TYPE_SCORE) {
                String satisfaction = "";
                RadioButton radioButton = (RadioButton) getView().findViewById(mBinding.rgView.getCheckedRadioButtonId());
                if (radioButton != null) {
                    satisfaction = StringUtils.checkStringIsNull(radioButton.getText().toString().trim());
                }
                mPresenter.userScore(mData.getCode(), satisfaction, mBinding.edtCause.getText().toString().trim());
            }
        } else {
            LoginActivity.startActivity(getActivity());
        }
    }

    public void startPlay(String filePath, final VoiceSoundView voiceSoundView) {
        if (mRxAudioPlayer != null) {
            if (mRxAudioPlayer.getMediaPlayer() != null && mRxAudioPlayer.getMediaPlayer().isPlaying()) {
                stopPlay(voiceSoundView);
            } else {
                File audioFile = new File(filePath);
                Logger.d("filepath==="+audioFile);
                if (audioFile.exists()) {
                    voiceSoundView.start(R.drawable.president_online_voice_sound);
                    mRxAudioPlayer.play(
                            PlayConfig.file(audioFile)
                                    .looping(false)
                                    .streamType(AudioManager.STREAM_VOICE_CALL)
                                    .build())
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new Observer<Boolean>() {
                                @Override
                                public void onSubscribe(final Disposable disposable) {

                                }

                                @Override
                                public void onNext(final Boolean aBoolean) {
                                    // prepared
                                }

                                @Override
                                public void onError(final Throwable throwable) {
                                    voiceSoundView.stop(R.mipmap.sounds3);
                                }

                                @Override
                                public void onComplete() {
                                    voiceSoundView.stop(R.mipmap.sounds3);
                                }
                            });
                }

            }
        }
    }

    public void stopPlay(VoiceSoundView voiceSoundView) {
        if (mRxAudioPlayer != null) {
            mRxAudioPlayer.stopPlay();
        }
        voiceSoundView.stop(R.mipmap.sounds3);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mRxAudioPlayer != null) {
            mRxAudioPlayer.stopPlay();
        }
        mPresenter.unbind();
    }
}
